package com.block.account.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.block.account.enums.AccountTypeEnum;
import com.block.account.enums.ActionTypeEnum;
import com.block.account.enums.ApplyStatusEnum;
import com.block.account.model.dto.ChangeAmountDTO;
import com.block.account.service.IAccountHandleService;
import com.block.common.annotate.RedisLock;
import com.block.common.constant.AppRspCodeConstant;
import com.block.common.service.LogFactory;
import com.block.common.vo.ResponseVo;
import com.block.db.entity.AccountApplyRecord;
import com.block.db.mapper.AccountApplyRecordMapper;
import com.block.account.service.IAccountApplyRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.time.LocalDateTime;

/**
 * <p>
 * 账户入账申请表 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-08-26
 */
@Service
public class AccountApplyRecordServiceImpl extends ServiceImpl<AccountApplyRecordMapper, AccountApplyRecord> implements IAccountApplyRecordService {

    private Logger log = LogFactory.getAccountLog();

    @Autowired
    IAccountHandleService accountHandleService;

    @Override
    @Transactional
    @RedisLock(lockName = "APPLY::RECORD::ENTER", key = "#applyRecordId" )
    public ResponseVo enterAccount(String applyRecordId, String operatorId, String operatorName) {

        AccountApplyRecord applyRecord = this.baseMapper.getApplyRecordByIdLock(applyRecordId);
        if (ObjectUtil.isEmpty(applyRecord)){
            return new ResponseVo(AppRspCodeConstant.PARAM_ERROR,"数据不存在");
        }
        if (!ObjectUtil.equals(applyRecord.getStatus(), ApplyStatusEnum.WAIT.getValue())){
            return new ResponseVo(AppRspCodeConstant.PARAM_ERROR,"状态错误，不允许操作");
        }

        log.info("【入账申请】【applyRecordId】{}【operatorId】{}【operatorName】{}", applyRecordId, operatorId, operatorName);

        // 更新申请的状态，
        AccountApplyRecord updateEntity = new AccountApplyRecord();
        updateEntity.setId(applyRecord.getId());
        updateEntity.setStatus(ApplyStatusEnum.SUCCESS.getValue());
        updateEntity.setUpdatorId(operatorId);
        updateEntity.setUpdatorName(operatorName);
        updateEntity.setUpdateTime(LocalDateTime.now());
        boolean updateRes = this.updateById(updateEntity);
        log.info("【入账申请】更新入账申请完成【updateRes】{}【applyRecordId】{}", updateRes, applyRecordId);
        if (!updateRes){
            return new ResponseVo(AppRspCodeConstant.SYS_EXCEPTION, "更新申请信息错误");
        }

        ChangeAmountDTO changeAmountDTO = new ChangeAmountDTO();
        changeAmountDTO.setChangeAmount(ActionTypeEnum.getChangeAmount(applyRecord.getActionType(), applyRecord.getBillAmount()));
        changeAmountDTO.setBillDateInfo(applyRecord.getBillDateInfo());
        changeAmountDTO.setAccountId(applyRecord.getItemAccountId());
        changeAmountDTO.setAccountName(applyRecord.getItemAccountName());
        changeAmountDTO.setMainAccountId(applyRecord.getMainAccountId());

        String remarkInfo = "入账备注：" + applyRecord.getRemarkInfo();
        if (StrUtil.equals(applyRecord.getActionType(), ActionTypeEnum.TZ.getValue())){
            remarkInfo = StrUtil.format("{}  【{}({})】调账转出到 【{}({})】",
                    remarkInfo, applyRecord.getItemAccountName(), applyRecord.getItemAccountId(),
                    applyRecord.getMainAccountName() , applyRecord.getMainAccountId());
        }

        changeAmountDTO.setRemarkInfo(remarkInfo);
        changeAmountDTO.setDataInfo("入账申请ID:"+String.valueOf(applyRecord.getId()));
        changeAmountDTO.setOperatorId(operatorId);
        changeAmountDTO.setOperatorName(operatorName);

        ActionTypeEnum actionTypeEnum = ActionTypeEnum.getEntityByType(applyRecord.getActionType());
        AccountTypeEnum accountTypeEnum = AccountTypeEnum.getEntityByType(applyRecord.getItemAccountType());

        changeAmountDTO.setActionTypeEnum(actionTypeEnum);
        changeAmountDTO.setAccountTypeEnum(accountTypeEnum);

        // 更新账户余额信息
        boolean changeRes = accountHandleService.changeAmountHandle(changeAmountDTO);
        log.info("【入账申请】入账操作执行结束【changeRes】{}【changeAmountDTO】{}", changeRes, JSON.toJSONString(changeAmountDTO));
        if (!changeRes){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResponseVo(AppRspCodeConstant.SYS_EXCEPTION, "操作失败");
        }

        return new ResponseVo(AppRspCodeConstant.SUCCESS);
    }
}
